<template>
  <div>
    <!-- layout布局 -->
    <el-row :gutter="20">
      <el-col :span="7">
        <el-input @change="getUserList" clearable placeholder="请输入内容" v-model.trim="queryInfo.query">
          <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button @click="addDialogVisible = true" type="primary">添加用户</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table border :data="userList" stripe style="width: 100%" height="450">
      <el-table-column type="index" label="#">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="role_name" label="角色">
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch @change="userStateChange(scope.row)" v-model="scope.row.mg_state">
          </el-switch>
        </template>

      </el-table-column>
      <!-- 操作按钮 -->
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="changeDialog(scope.row)" icon="el-icon-edit"></el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUser(scope.row)"></el-button>
          <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
            <el-button size="mini" type="warning" icon="el-icon-s-tools" @click="showRolesDialog(scope.row)"></el-button>
          </el-tooltip>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[2, 4, 8, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 添加用户弹出框 -->
    <el-dialog v-dialogDrag title="添加用户" :visible.sync="addDialogVisible" @close="closeAddDialog" width="50%">
      <!-- 表单 -->
      <el-form :rules="addUserFromRuls" ref="addUserFromRef" :model="addUserFrom">
        <el-form-item prop="username" label-width="70px" label="用户名">
          <el-input v-model="addUserFrom.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" label-width="70px" label="密码">
          <el-input v-model="addUserFrom.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="email" label-width="70px" label="邮箱">
          <el-input v-model="addUserFrom.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label-width="70px" label="手机号">
          <el-input v-model="addUserFrom.mobile" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog v-dialogDrag title="修改用户" :visible.sync="changeDialogStu" @close="changeUserDialog" width="50%">
      <!-- 修改对话框表单 -->
      <el-form :rules="addUserFromRuls" ref="changeUserFromRef" :model="changeUserFrom">
        <el-form-item label-width="70px" label="用户名">
          <el-input disabled v-model="changeUserFrom.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="email" label-width="70px" label="邮箱">
          <el-input v-model="changeUserFrom.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label-width="70px" label="手机号">
          <el-input v-model="changeUserFrom.mobile" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialogStu=false">取 消</el-button>
        <el-button type="primary" @click="changeUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <!-- 添加用户弹出框 -->
    <el-dialog @close="rolesNow='';userInfo={};userId=''" v-dialogDrag title="分配角色" :visible.sync="setRolesDialog" width="50%">

      <div class="userRoles">
        <p>当前用户的名称: {{userInfo.username}}</p>
        <p>当前用户的角色: {{userInfo.rolename}}</p>
      </div>
      分配新的角色：
      <el-select @change="logs" v-model="rolesNow" placeholder="请选择">
        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
        </el-option>
      </el-select>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialog=false">取 消</el-button>
        <el-button type="primary" @click="putUserRoles">确 定</el-button>
      </span>

    </el-dialog>
  </div>
</template>

<script>
import { getUsersAPI, putUsersAPI, postUsersAPI, putUsersStuAPI, deleteUsersAPI } from '@/api/homeAPI.js'
import { getUserPowerListAPI, putUserRolesAPI } from '@/api/powerAPI'

export default {
  name: 'user',
  data() {
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 用户列表
      userList: [],
      // 角色列表
      rolesList: [],
      // 列表总数
      total: 0,
      // 添加用户弹出框
      addDialogVisible: false,
      // 用户修改弹出框
      changeDialogStu: false,
      // 分配角色弹出框
      setRolesDialog: false,
      // 添加用户表单
      addUserFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      changeUserFrom: {
        username: '',
        email: '',
        mobile: ''
      },
      // 选中的userid
      userId: 0,
      addUserFromRuls: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, message: '请输入合法手机号/电话号', trigger: ['blur', 'change'] }
        ]
      },
      userInfo: {
        username: '',
        rolename: ''
      },
      rolesNow: ''
    }
  },
  methods: {
    logs() {
      console.log(this.rolesNow)
    },
    async getUserList() {
      const { data: res } = await getUsersAPI(this.queryInfo)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 获取角色
    async getRolesList() {
      const { data: res } = await getUserPowerListAPI()

      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 分页
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 更新用户状态
    async userStateChange(row) {
      const { data: res } = await putUsersStuAPI({
        id: row.id,
        state: row.mg_state
      })
      if (res.meta.status !== 200) {
        this.userList.mg_state = !this.userList.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 新增用户
    addUser() {
      this.$refs.addUserFromRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await postUsersAPI(this.addUserFrom)

        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        } else {
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    changeDialog(row) {
      this.changeDialogStu = true
      this.changeUserFrom.username = row.username
      this.changeUserFrom.email = row.email
      this.changeUserFrom.mobile = row.mobile
      this.userId = row.id
    },
    changeUser() {
      this.$refs.changeUserFromRef.validate(async valid => {
        if (!valid) {
          return false
        } else {
          const { data: res } = await putUsersAPI({
            id: this.userId,
            email: this.changeUserFrom.email,
            mobile: this.changeUserFrom.mobile
          })
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('更新成功')
          this.changeDialogStu = false
          this.getUserList()
        }
      })
    },
    // 删除用户
    async deleteUser(row) {
      const confirResult = await this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirResult)
      if (confirResult === 'confirm') {
        const { data: res } = await deleteUsersAPI(row.id)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('删除成功')
        this.getUserList()
      }
    },
    // 关闭对话框重置
    closeAddDialog() {
      console.log(this.$refs)

      // 添加用户表单
      this.addUserFrom = {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }
      this.$refs.addUserFromRef.resetFields()
    },
    // 关闭修改对话框
    changeUserDialog() {
      console.log(this.$refs)
      this.$refs.changeUserFromRef.resetFields()
    },
    // 分配角色对话框
    showRolesDialog(row) {
      this.getRolesList()
      this.userId = row.id
      this.userInfo.username = row.username
      this.userInfo.rolename = row.role_name
      this.setRolesDialog = true
    },
    // 分配角色提交
    async putUserRoles() {
      if (!this.rolesNow) return this.$message.error('请选择要分配的角色')
      const { data: res } = await putUserRolesAPI(this.userId, this.rolesNow)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.setRolesDialog = false
      this.$message.success('修改成功')
      this.getUserList()
    }
  },

  created() {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;
  .el-table {
    margin-top: 10px;
    font-size: 12px;
    // transition: all 0.5s;
  }
  .userRoles {
    p {
      margin: 20px 0;
    }
  }
}
</style>
